// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2024 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.7
package sys

import (
	"context"
	"fmt"
	"hotgo/internal/dao"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/model/input/form"
	"hotgo/internal/model/input/store"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"
	"hotgo/utility/validate"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

type sSysStoreProduct struct{}

func NewSysStoreProduct() *sSysStoreProduct {
	return &sSysStoreProduct{}
}

func init() {
	service.RegisterSysStoreProduct(NewSysStoreProduct())
}

// Model 商品ORM模型
func (s *sSysStoreProduct) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.StoreProduct.Ctx(ctx), option...)
}

// List 获取商品列表
func (s *sSysStoreProduct) List(ctx context.Context, in *store.StoreProductListInp) (list []*store.StoreProductListModel, totalCount int, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.Fields(store.StoreProductListModel{})

	// 查询商品标题
	if in.Title != "" {
		mod = mod.WhereLike(dao.StoreProduct.Columns().Title, in.Title)
	}

	// 查询是否热门
	if in.IsHot > 0 {
		mod = mod.Where(dao.StoreProduct.Columns().IsHot, in.IsHot)
	}

	// 查询上架状态
	if in.Status > 0 {
		mod = mod.Where(dao.StoreProduct.Columns().Status, in.Status)
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderAsc(dao.StoreProduct.Columns().Sort).OrderDesc(dao.StoreProduct.Columns().Id)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取商品列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出商品
func (s *sSysStoreProduct) Export(ctx context.Context, in *store.StoreProductListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(store.StoreProductExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出商品-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []store.StoreProductExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增商品
func (s *sSysStoreProduct) Edit(ctx context.Context, in *store.StoreProductEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 修改
		if in.Id > 0 {
			if _, err = s.Model(ctx).
				Fields(store.StoreProductUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.Wrap(err, "修改商品失败，请稍后重试！")
				return
			}
		} else {
			// 新增
			r, _ := s.Model(ctx, &handler.Option{FilterAuth: false}).
				Fields(store.StoreProductInsertFields{}).
				Data(in).OmitEmptyData().Insert()
			id, _ := r.LastInsertId()
			in.Id = id
		}

		if in.Id > 0 {
			dao.StoreProductSku.Ctx(ctx).Where("product_id", in.Id).Delete()
			dao.StoreProductAttr.Ctx(ctx).Where("product_id", in.Id).Delete()
			dao.StoreProductImage.Ctx(ctx).Where("product_id", in.Id).Delete()
			dao.StoreProductContent.Ctx(ctx).Where("product_id", in.Id).Delete()
			skuData := &store.StoreProductSku{}
			attrDate := &store.StoreProductAttr{}
			imageData := &store.StoreProductImage{}
			contentData := &store.StoreProductContent{}

			contentData.ProductId = in.Id
			contentData.Content = in.Content
			dao.StoreProductContent.Ctx(ctx).Data(contentData).Insert()
			for _, v := range in.Skus {
				skuData.ProductId = in.Id
				skuData.Price = v.Price
				skuData.Stock = v.Stock
				skuData.Name = v.Name
				skuData.Code = v.Code
				if _, err = dao.StoreProductSku.Ctx(ctx).Data(skuData).Insert(); err != nil {
					err = gerror.Wrap(err, "添加商品规格失败，请稍后重试！")
					continue
				}
			}
			for _, v := range in.Attrs {
				attrDate.ProductId = in.Id
				attrDate.Name = v.Name
				attrDate.Value = v.Value
				if _, err = dao.StoreProductAttr.Ctx(ctx).Data(attrDate).Insert(); err != nil {
					err = gerror.Wrap(err, "添加商品属性失败，请稍后重试！")
					continue
				}
			}
			for _, v := range in.Images {
				imageData.ProductId = in.Id
				imageData.Image = v.Image
				if _, err = dao.StoreProductImage.Ctx(ctx).Data(imageData).Insert(); err != nil {
					err = gerror.Wrap(err, "添加商品图片失败，请稍后重试！")
					continue
				}
			}
		}
		return
	})
}

// Delete 删除商品
func (s *sSysStoreProduct) Delete(ctx context.Context, in *store.StoreProductDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Delete(); err != nil {
		err = gerror.Wrap(err, "删除商品失败，请稍后重试！")
		return
	}
	return
}

// MaxSort 获取商品最大排序
func (s *sSysStoreProduct) MaxSort(ctx context.Context, in *store.StoreProductMaxSortInp) (res *store.StoreProductMaxSortModel, err error) {
	if err = dao.StoreProduct.Ctx(ctx).Fields(dao.StoreProduct.Columns().Sort).OrderDesc(dao.StoreProduct.Columns().Sort).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取商品最大排序，请稍后重试！")
		return
	}

	if res == nil {
		res = new(store.StoreProductMaxSortModel)
	}

	res.Sort = form.DefaultMaxSort(res.Sort)
	return
}

// View 获取商品指定信息
func (s *sSysStoreProduct) View(ctx context.Context, in *store.StoreProductViewInp) (res *store.StoreProductViewModel, err error) {
	if err = s.Model(ctx).WithAll().WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取商品信息，请稍后重试！")
		return
	}
	return
}

// Status 更新商品状态
func (s *sSysStoreProduct) Status(ctx context.Context, in *store.StoreProductStatusInp) (err error) {
	if _, err = s.Model(ctx).WherePri(in.Id).Data(g.Map{
		dao.StoreProduct.Columns().Status: in.Status,
	}).Update(); err != nil {
		err = gerror.Wrap(err, "更新商品状态失败，请稍后重试！")
		return
	}
	return
}

// Switch 更新商品开关
func (s *sSysStoreProduct) Switch(ctx context.Context, in *store.StoreProductSwitchInp) (err error) {
	var fields = []string{
		dao.StoreProduct.Columns().IsHot,
		dao.StoreProduct.Columns().Status,
		// ...
	}

	if !validate.InSlice(fields, in.Key) {
		err = gerror.New("开关键名不在白名单")
		return
	}

	if _, err = s.Model(ctx).WherePri(in.Id).Data(g.Map{
		in.Key: in.Value,
	}).Update(); err != nil {
		err = gerror.Wrap(err, "更新商品开关失败，请稍后重试！")
		return
	}
	return
}
